#ifndef __CORE_TCPSERVER_H__
#define __CORE_TCPSERVER_H__

#define WIN32_LEAN_AND_MEAN
#define _WINSOCK_DEPRECATED_NO_WARNINGS

#include <WinSock2.h>
#include <windows.h>
#include <WS2tcpip.h> //socklen_t
#include <string.h>
#include <stdio.h>
#include <vector>
#include <map>
#include <thread>
#include <mutex>
#include <atomic>
#pragma comment(lib,"ws2_32.lib")

#include "core_netevent.h"
#include "core_timestamp.h"
#include "core_thread.h"

class CoreCellServer
{
private:
	int id;
	CoreThread cthread;
	CoreNetEvent* netevent;
	std::map<SOCKET, CoreClient*> clients;
	std::vector<CoreClient*> clientsBuff;
	std::mutex mymutex;
	SOCKET maxsockfd;
	fd_set fdRead_back;
	bool clients_change;

public:
	CoreCellServer(int id);
	~CoreCellServer();
	void start();
	void onRun(CoreThread* pthread);
	void addClient(int csocketfd);
	void removeClient(CoreClient* del);
	int getClientCount();
	void setNetEvent(CoreNetEvent* ev);
	int dataReceived(CoreClient* pclient);
};



class CoreServer : public CoreNetEvent
{
private:
	SOCKET sockfd;
	std::vector<CoreCellServer *> cellservers;
	CoreTimestamp _tTime;
	std::atomic_int _recvCount;
	int _clientCount;
	CoreThread cthread;
	
public:
	CoreServer();
	virtual ~CoreServer();
	void createSocket();
	void closeSocket();
	int bind(const char* ip, unsigned short port);
	int listen(int n);
	void start(int threadcount);
	
	virtual void onClientConnectionMade(CoreClient* client);
	virtual void onClientConnectionLost(CoreClient* client);
	virtual void onDataReceived(CoreClient* client);
	virtual void onPacketReceived(CoreClient* client, CoreStream* data);
	
private:
	void accept();
	void time4msg();
	void onRun(CoreThread* pthread);
};


#endif